﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ItemQuoteLibrary
{
    public class ItemQuoteDecoderText:ItemQuoteDecoder
    {
        public Encoding EncodingType { get; private set; }

        public ItemQuoteDecoderText(string encodingType)
        {
            EncodingType = Encoding.GetEncoding(encodingType);
        }

        public ItemQuoteDecoderText()
            : this(ItemQuoteTextConst.DEFAULT_CHAR_ENC)
        {            
        }

        public ItemQuote Decode(Stream stream)
        {

            byte[] space = EncodingType.GetBytes(" ");
            byte[] newLine = EncodingType.GetBytes("\n");

            string itemNo = EncodingType.GetString(Framer.nextToken(stream, space));
            string description = EncodingType.GetString(Framer.nextToken(stream, newLine));
            string quantity = EncodingType.GetString(Framer.nextToken(stream, space));
            string price = EncodingType.GetString(Framer.nextToken(stream, space));
            string flags = EncodingType.GetString(Framer.nextToken(stream, newLine));

            return new ItemQuote(Int64.Parse(itemNo),
                description,
                Int32.Parse(quantity),
                Int32.Parse(price),
                flags.IndexOf("d") != -1,
                flags.IndexOf("s") != -1);
        }

        public ItemQuote Decode(byte[] packet)
        {
            Stream stream = new MemoryStream(packet, 0, packet.Length, false);
            return Decode(stream);            
        }
    }
}
